import 'dart:async';
import 'dart:convert';

import 'package:data_table_2/data_table_2.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:yuellyfactory/util/MathUtil.dart';
import 'package:yuellyfactory/views/dto/PricePart.dart';
import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshTree.dart';
import '../../eventbus/EventRefreshType.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/DialogUtil.dart';
import '../../util/GlobalData.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../../util/XNumberTextInputFormatter.dart';

class EditTypeView extends StatefulWidget {
  const EditTypeView({super.key});

  @override
  State<EditTypeView> createState() => _EditTypeViewState();
}

class _EditTypeViewState extends State<EditTypeView> {

  final formKey = GlobalKey<ShadFormState>();
  StreamSubscription? streamSubscription;
  PricePart pricePart=PricePart();
  final TextEditingController _nameController = TextEditingController();
  Map<String,bool> showMaps={};


  final dialogKey = GlobalKey<ShadFormState>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    streamSubscription = eventBus.on<EventRefreshType>().listen((event) {
      pricePart=event.pricePart;
      _nameController.text=pricePart!.name;
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    if (streamSubscription != null) {
      streamSubscription!.cancel();
    }
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [

          if(pricePart!.type=='type')
            Text(
            //   '${pricePart!.type=='type'?"分类":(
            //     pricePart!.type=='serial'?"产品系列":"机型"
            // )} :'
                  '${pricePart!.name}'

              ,style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),



          if(pricePart!.type=='serial')
            Text(
            //   '${pricePart!.type=='type'?"分类":(
            //     pricePart!.type=='serial'?"产品系列":"机型"
            // )} : '
                '${getCrumbName()}'

              ,style: TextStyle(fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),

          if(pricePart!.type=='product')
          Row(
            children: [
              Text(
              //   '${pricePart!.type=='type'?"分类":(
              //     pricePart!.type=='serial'?"产品系列":"机型"
              // )} : '
                  '${getCrumbName()}',style: TextStyle(fontSize: ViewUtil.fontSize(28),fontWeight: FontWeight.bold),),
              SizedBox(width: ViewUtil.screenWidth(20),),
              Expanded(child: Container()),
              ViewUtil.configIcon('型号设置',(){

              })

            ],
          ),
          ViewUtil.lineView(),
          SizedBox(height: ViewUtil.screenHeight(10),),
          if(pricePart!.type=='type'||pricePart!.type=='serial')
            Column(children: childView(),),


        ],
    );
  }




  List<Widget> childView(){
    List<Widget> widgets=[];
    for(PricePart partData in pricePart.priceModels){
      widgets.add(
          Row(
            children: [
              SizedBox(width: ViewUtil.screenWidth(15),),
              GestureDetector(onTap: (){
                eventBus.fire(EventRefreshTree(partData.id));
              },child:

              Container(width: ViewUtil.screenWidth(300),
                child: Text('${partData.type=='serial'?'产品系列':'机型'} : ${partData.name}',style: TextStyle(fontSize: ViewUtil.fontSize(22),),),
              )

              ),

              if(partData.type=='product')
                Text('   Code : ${partData.code}   毛利率 : ${MathUtil.formatDouble(double.parse(partData.grossMargin), 2)}%   利润率 : ${MathUtil.formatDouble(double.parse(partData.profitMargin), 2)}%   零售价比例 : ${MathUtil.formatDouble(double.parse(partData.retailRatio), 2)}%',style: TextStyle(fontSize: ViewUtil.fontSize(22),),),

              SizedBox(width: ViewUtil.screenWidth(20),),
              Expanded(child: Container()),
              if(partData.type=='product')
              IconButton(icon:  Icon( getIsShow(partData.id)?Icons.keyboard_arrow_down_outlined:Icons.keyboard_arrow_right_outlined),
                color:ColorUtil.colorBlue,
                iconSize: ViewUtil.screenWidth(35),onPressed: (){
                  bool result= getIsShow(partData.id);
                  result=!result;
                  showMaps[partData.id]=result;
                  setState(() {

                  });
                },),


              ViewUtil.editIcon("编辑${partData.type=='serial'?'产品系列':'机型'}", (){
                editType(partData);
              }),
              ViewUtil.delIcon("删除${partData.type=='serial'?'产品系列':'机型'}", (){
                showDelPart(partData);
              }),
            ],
          )
      );




      if(partData.type=='product'){

        widgets.add(Visibility(
            visible: getIsShow(partData.id),
            child: Row(
              children: [
                SizedBox(width: ViewUtil.screenWidth(30),),
                Text('折扣配置',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                Expanded(child: Container()),
                ViewUtil.addIcon('新增折扣配置',(){
                  showDiscountDialog(partData,{"max":"","value":""},getDiscountList(partData));
                }),
              ],
            ),
        ));
        widgets.add(Visibility(
            visible: getIsShow(partData.id),
            child: discountView(partData)));

        widgets.add(Visibility(
            visible: getIsShow(partData.id),
            child: Row(
              children: [
                SizedBox(width: ViewUtil.screenWidth(30),),
                Text('机型概况',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22)),),
                Expanded(child: Container()),
                ViewUtil.addIcon('新增机型概况',(){
                  showSpecDialog(partData,{"name":"","value":""},getSpecList(partData));
                }),
              ],
            ),

        ));

        widgets.add(Visibility(
            visible: getIsShow(partData.id),
            child: specView(partData)));

      }
    }

    return widgets;
  }

  getSpecList(PricePart partData){
    if(partData.remarkData.isNotEmpty){
      return jsonDecode(partData.remarkData);
    }else{
      return [];
    }
  }

  getDiscountList(PricePart partData){
    if(partData.discount.isNotEmpty){
      return jsonDecode(partData.discount);
    }else{
      return [];
    }
  }

  // 固定高度参数（可根据需求调整）
  final double _headerHeight = 56; // 表头高度（含内边距）
  final double _rowHeight = 48; // 每行高度（含内边距）
  final double _borderWidth = 1; // 边框宽度
  final double _outerPadding = 10; // 表格外间距

  // 计算表格总高度的核心方法
  double _calculateTableHeight(int length) {
    // 总高度 = 表头高度 + 数据行总高度 + 边框总高度
    // 边框高度：上下边框（2条）+ 行之间的分隔线（数据行数-1条）
    final int borderCount = 2 + (length - 1);
    final double totalBorderHeight = borderCount * _borderWidth;

    return _headerHeight + // 表头高度
        (_rowHeight * length) + // 所有数据行高度
        totalBorderHeight; // 边框总高度
  }



  void showDiscountDialog(PricePart partData,var item,List discountList){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: const Text('确定'),onPressed: (){
              if (dialogKey.currentState!.saveAndValidate()) {
                var values = dialogKey.currentState!.value;
                var max=values["max"];
                var value=values["value"];
                if(item["max"].length==0){
                  item["max"]=max;
                  item["value"]=value;
                  discountList.add(item);

                }else{
                  item["max"]=max;
                  item["value"]=value;
                }
                saveModelDiscount(partData,discountList,true);
              }
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ShadInputFormField(
                    id: 'max',
                    initialValue: item["max"],
                    label: const Text('数量上限(台)'),
                    placeholder: const Text('请输入数量上限'),
                    keyboardType: const TextInputType.numberWithOptions(decimal: false),
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp("[0-9]")),
                      XNumberTextInputFormatter(
                          maxIntegerLength: null,
                          maxDecimalLength: 0,
                          isAllowDecimal: true),
                    ],
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入数量上限';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  ShadInputFormField(
                    id: 'value',
                    initialValue: item["value"],
                    label: const Text('折扣(%)'),
                    placeholder: const Text('请输入折扣'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入折扣';
                      }
                      return null;
                    },
                    keyboardType: const TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: [
                      FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                      XNumberTextInputFormatter(
                          maxIntegerLength: null,
                          maxDecimalLength: 2,
                          isAllowDecimal: true),
                    ],
                  )


                ],
              )

              ,)

        )
    );
  }


  Widget discountView(PricePart partData){
    List discountList=getDiscountList(partData);
    final double tableHeight = _calculateTableHeight(discountList.length);
    return // 表格（高度固定为计算值）
      Padding(
        padding: EdgeInsets.symmetric(horizontal: _outerPadding),
        child: Container(
          // 应用计算出的高度
          height: tableHeight,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
            borderRadius: BorderRadius.circular(8),
          ),
          child: DataTable2(
            columnSpacing: 12,
            //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
            minWidth: 500,
            headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
            dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
            // 表头
            columns: const [
              DataColumn2(
                label: Text('  操作'),
                fixedWidth: 140,
              ),
              DataColumn2(
                label: Text('数量上限(台)'),
                size: ColumnSize.L,

              ),
              DataColumn2(
                label: Text('折扣(%)'),
                size: ColumnSize.L,
              ),
            ],

            // 表格内容（行高固定）
            rows: discountList.map((item) {
              return DataRow(cells: [
                DataCell(
                  Row(
                    children: [
                      ViewUtil.editIcon('编辑折扣',(){
                        showDiscountDialog(partData,item,discountList);
                      }),
                      ViewUtil.delIcon('删除折扣',(){
                        discountList.remove(item);
                        saveModelDiscount(partData,discountList,false);
                      }),

                    ],
                  ),
                ),
                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["max"]??""),
                )),

                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["value"]??""+"%"),
                )),

              ]);
            }).toList(),
          ),
        ),
      );
  }


  Widget specView(PricePart partData){
    List specsList=getSpecList(partData);
    final double tableHeight = _calculateTableHeight(specsList.length);
    return // 表格（高度固定为计算值）
      Padding(
        padding: EdgeInsets.symmetric(horizontal: _outerPadding),
        child: Container(
          // 应用计算出的高度
          height: tableHeight,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.grey[200]!, width: _borderWidth),
            borderRadius: BorderRadius.circular(8),
          ),
          child: DataTable2(
            columnSpacing: 12,
            //  minWidth: MediaQuery.of(context).size.width - 2 * _outerPadding,
            minWidth: 500,
            headingRowHeight: _headerHeight - 2 * _borderWidth, // 减去边框占用高度
            dataRowHeight: _rowHeight - 2 * _borderWidth, // 减去边框占用高度
            // 表头
            columns: const [
              DataColumn2(
                label: Text('  操作'),
                fixedWidth: 140,
              ),
              DataColumn2(
                label: Text('名称'),
                size: ColumnSize.L,

              ),
              DataColumn2(
                label: Text('参数'),
                size: ColumnSize.L,
              ),
            ],

            // 表格内容（行高固定）
            rows: specsList.map((item) {
              return DataRow(cells: [
                DataCell(
                  Row(
                    children: [
                      ViewUtil.editIcon('编辑概述',(){
                        showSpecDialog(partData,item,specsList);
                      }),
                      ViewUtil.delIcon('删除概述',(){
                        specsList.remove(item);
                        saveModelRemark(partData,specsList,false);
                      }),

                    ],
                  ),
                ),
                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["name"]),
                )),

                DataCell(Padding(
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  child: Text(item["value"]),
                )),

              ]);
            }).toList(),
          ),
        ),
      );
  }

  void showSpecDialog(PricePart partData,var item,List specsList){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: const Text('确定'),onPressed: (){
              if (dialogKey.currentState!.saveAndValidate()) {
                var values = dialogKey.currentState!.value;
                var name=values["name"];
                var value=values["value"];
                if(item["name"].length==0){
                  item["name"]=name;
                  item["value"]=value;
                  specsList.add(item);

                }else{
                  item["name"]=name;
                  item["value"]=value;
                }
                saveModelRemark(partData,specsList,true);
              }
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ShadInputFormField(
                    id: 'name',
                    initialValue: item["name"],
                    label: const Text('概述名称'),
                    placeholder: const Text('请输入概述名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入概述名称';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  ShadInputFormField(
                    id: 'value',
                    initialValue: item["value"],
                    label: const Text('概述参数'),
                    placeholder: const Text('请输入概述参数'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入概述参数';
                      }
                      return null;
                    },
                  )


                ],
              )

              ,)

        )
    );
  }


  getCrumbName(){
    List list= ViewUtil.crumbModelList(pricePart.id,GlobalData.modelData);
    var name="";
    for(var i=0;i<list.length;i++){
      PricePart part=list[i];
      name=name+part.name;
      if(i!=list.length-1){
        name="$name > ";
      }
    }
    return name;
  }


  void saveModelRemark(PricePart partData,List specsList,bool popDialog){
    String jsonString = jsonEncode(specsList);
    var parm={
      "remark":jsonString,
      "id":partData.id,
    };
    BaseRequest.postHttp("price/modelremark",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        partData.remarkData=jsonString;
        setState(() {

        });
        ToastUtil.showToast("编辑成功");
        eventBus.fire(EventRefreshBase());
        if(popDialog){
          Navigator.pop(context);
        }

      }
    }, onError: (error){

    });



  }


  void saveModelDiscount(PricePart partData,List discountList,bool popDialog){
    //做一下排序
    var mutableList = List.from(discountList);
    mutableList.sort((a, b) {
      // 处理 null 值，这里将 null 视为 0 或其他默认值
      int maxA = int.tryParse(a["max"] ?? "") ?? 0;
      int maxB = int.tryParse(b["max"] ?? "") ?? 0;
      return maxB.compareTo(maxA);
    });
    String jsonString = jsonEncode(mutableList);
    var parm={
      "discount":jsonString,
      "id":partData.id,
    };
    BaseRequest.postHttp("price/modeldiscount",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        partData.discount=jsonString;
        setState(() {

        });
        ToastUtil.showToast("编辑成功");
        eventBus.fire(EventRefreshBase());
        if(popDialog){
          Navigator.pop(context);
        }

      }
    }, onError: (error){

    });



  }




  getIsShow(String id){
    bool result=false;
    if(showMaps.containsKey(id)){
      return showMaps[id];
    }
    return result;
  }

  void showDelPart(PricePart partData){
    DialogUtil.showConfimDialog(context, "确定删除${partData.name}", "确定将删除${partData.name}", "确定", (){
      uploadDelModel(partData);
    });
  }

  void uploadDelModel(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/modeldel",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        eventBus.fire(EventRefreshBase());
      }
    }, onError: (error){

    });
  }


  void editType(PricePart partData){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitType(partData);
            },)],
            child:
            ShadForm(
              key: formKey,
              child: Column(
                children: [
                  ShadInputFormField(
                    id: 'name',
                    label: const Text('名称'),
                    placeholder: const Text('请输入名称'),
                    initialValue: partData.name,
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入名称';
                      }
                      return null;
                    },
                  ),
                  if(partData.type=='product')
                    ShadInputFormField(
                      id: 'code',
                      label: const Text('Code'),
                      placeholder: const Text('请输入Code'),
                      initialValue: partData.code,
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入Code';
                        }
                        return null;
                      },
                    ),
                  if(partData.type=='product')
                    ShadInputFormField(
                      id: 'grossMargin',
                      label: const Text('毛利率(如10%,直接输入10'),
                      suffix: const Text("%"),
                      placeholder: const Text('请输入毛利率'),
                      initialValue: MathUtil.formatDouble(double.parse(partData.grossMargin), 2),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入毛利率';
                        }
                        return null;
                      },
                    ),
                  if(partData.type=='product')
                    ShadInputFormField(
                      id: 'profitMargin',
                      label: const Text('利润率(如10%,直接输入10'),
                      suffix: const Text("%"),
                      placeholder: const Text('请输入利润率'),
                      initialValue: MathUtil.formatDouble(double.parse(partData.profitMargin), 2),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入利润率';
                        }
                        return null;
                      },
                    ),
                  if(partData.type=='product')
                    ShadInputFormField(
                      id: 'retailRatio',
                      label: const Text('零售价比例(如10%,直接输入10'),
                      suffix: const Text("%"),
                      placeholder: const Text('请输入零售价比例'),
                      initialValue: MathUtil.formatDouble(double.parse(partData.retailRatio), 2),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入零售价比例';
                        }
                        return null;
                      },
                    ),
                ],
              )

            )

        )
    );
  }





  void submitType(PricePart partData) {
    if (formKey.currentState!.saveAndValidate()) {
      var values = formKey.currentState!.value;
      var name = values["name"];
      var code=values["code"];
      var grossMargin=values["grossMargin"];
      var profitMargin=values["profitMargin"];
      var retailRatio=values["retailRatio"];
      if(partData.type!='product'){
        code="";
        grossMargin="";
        profitMargin="";
        retailRatio="";
      }
      var parm = {
        "name": name,
        "code":code,
        "grossMargin":grossMargin,
        "profitMargin":profitMargin,
        "retailRatio":retailRatio,
        "parentId": partData.parentId,
        "type": partData.type,
        "id":partData.id,
      };
      BaseRequest.postHttp('price/edittype', parameters: parm,
          canTip: true,
          context: context,
          onSuccess: (data) {
            bool result = BaseRequest.chekResponse(data, true);
            if (result) {
              ToastUtil.showToast("编辑成功");
              eventBus.fire(EventRefreshBase());
              Navigator.pop(context);
            }
          },
          onError: (error) {

          });
    }
  }

}
